package tools;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Objects;

/**
 * Created by yangxianming on 2018/1/15.
 */
public class DateDeviation {
//    public static void main(String[] args) {
//        System.out.println(deviation("2"));
//    }

    public static String deviation(String str){
        //str第一个参数是current,默认为当前时间。一般格式为2016-05-05 17:30:00
        //默认偏移量为月
        //例子: current,month,-2,yyyy-MM-dd HH:mm:ss    2016-05-05 17:30:00,month,-2,yyyy-MM-dd HH:mm:ss
//        String str = "current,month," + offSet + ",yyyy-MM-dd HH:mm:ss";
        HashMap<String, Integer> dateSign = new HashMap<String, Integer>();
        dateSign.put("year", Calendar.YEAR);
        dateSign.put("month", Calendar.MONTH);
        dateSign.put("date", Calendar.DATE);
        dateSign.put("hour", Calendar.HOUR);
        dateSign.put("minute", Calendar.MINUTE);
        dateSign.put("second", Calendar.SECOND);

        String[] strings = str.split(",");
        for (int i = 0; i < strings.length; i++)
            strings[i] = strings[i].trim(); //去空格

        //格式化时间。如果有需要再加入hour minute second
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String setDay = strings[0];     //第一个参数的原始日期
        int deviation = Integer.valueOf(strings[2]);    //第三个参数的偏移量

        Calendar calendar = Calendar.getInstance();
        try {
            if (Objects.equals(setDay, "current")){
                setDay = sdf.format(new Date());
            }
            calendar.setTime(sdf.parse(setDay));
        }catch (Exception e){
            e.printStackTrace();
        }
        calendar.add(dateSign.get(strings[1]), deviation);  //设置日期偏移量
        //获取输出时间格式
        String outDateFormat = "yyyy-MM-dd";
        try {
            outDateFormat = strings[3];
        }catch (Exception e){
            System.out.println("DateAdd fourth parameter null, outDateFormat get the default value: yyyy-MM-dd");
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat(outDateFormat);
        String s = sdf1.format(calendar.getTime());
        return s;
    }
}
